package com.jiusit.common;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.webbuilder.common.Var;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 油卡申请表生成处理器
 * 
 * @author guoyb
 * 
 */
public class DocumentHandler {
	private static final Logger logger = LoggerFactory
			.getLogger(DocumentHandler.class);
	private Configuration configuration = null;

	public DocumentHandler() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}

	/**
	 * 合同模版生成处理
	 * 
	 * @param dataMap
	 *            参数对象。以KEY VALUE的形式存放
	 * @param templateName
	 *            模版文件名，无需带后缀
	 * @param fileName
	 *            生成后的文件名，无需带后缀
	 * @throws UnsupportedEncodingException
	 */
	public boolean createDoc(Map<String, Object> dataMap, String templateName,
			String fileName) throws Exception {
		String templatePath = Var.get("api.templatePath");
		String outFilePath = Var.get("api.outFilePath");
		String outFileSuffix = Var.get("api.outFileSuffix");
		/*String templatePath = "D:\\";
		String outFilePath = "D:\\";
		String outFileSuffix = ".xls";*/
		
		logger.info("templatePath:"+templatePath);
		logger.info("outFilePath:"+outFilePath);
		logger.info("outFileSuffix:"+outFileSuffix);
		// dataMap 要填入模本的数据文件
		Template t = null;
		try {
			
			// 设置模本装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet，classpath，数据库装载，
			configuration
					.setDirectoryForTemplateLoading(new File(templatePath));
			// test.ftl为要装载的模板
			t = configuration.getTemplate(templateName + ".xml");
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		// 输出文档路径及名称
		File outFile = new File(outFilePath + "/" + fileName + outFileSuffix);
		Writer out = null;
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(outFile);
			OutputStreamWriter oWriter = new OutputStreamWriter(fos, "UTF-8");
			// 这个地方对流的编码不可或缺，使用main（）单独调用时，应该可以，但是如果是web请求导出时导出后word文档就会打不开，并且包XML文件错误。主要是编码格式不正确，无法解析。
			// out = new BufferedWriter(new OutputStreamWriter(new
			// FileOutputStream(outFile)));
			out = new BufferedWriter(oWriter);
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
			return false;
		}

		try {
			t.process(dataMap, out);
			out.close();
			fos.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/**
	 * 调用实例
	 * 
	 * @param args
	 */
	public static void main(String[] args) {
		DocumentHandler dd = new DocumentHandler();
		Map dataMap = new HashMap();
		dataMap.put("NAME", "郭颖彬");
		dataMap.put("SEX", "女");
		try {
			dd.createDoc(dataMap, "002", "ccc合同20150910");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
